package com.ego.product.handler;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ego.common.constant.SystemConstant;
import com.ego.common.util.Result;
import com.ego.common.vo.order.PayAsyncVo;
import com.ego.product.component.AlipayTemplate;
import com.ego.product.feign.OrderFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: ego
 * @description: 订单支付成功处理器
 * @author: KamTang
 * @create: 2022-12-27 15:38
 **/
@RestController
@Slf4j
public class OrderPayedHandler {

    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private OrderFeign orderFeign;

    /**
     * 支付宝成功异步通知
     */
    @PostMapping("/payed/notify")
    public String payed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
        // 获取支付宝POST过来反馈信息
        Map<String, String[]> requestParams = request.getParameterMap();
        int size = request.getParameterMap().keySet().size();
        Map<String, String> params = new HashMap<>(size);
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayTemplate.getAlipayPublicKey(),
                alipayTemplate.getCharset(),
                alipayTemplate.getSignType());
        if (signVerified) {
            Result handlePayResult = orderFeign.handlePayResult(vo);
            log.info("支付结果handlePayResult => {}", handlePayResult);
            if (handlePayResult.getCode() == SystemConstant.Status.SUCCESS.getCode()) {
                return "success";
            } else {
                return "fail";
            }
        } else {
            log.info("签名验证失败");
            return "fail";
        }
    }

}
